package Other.Course;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

//207. 课程表
public class Course {
    
}


//拓扑排序
class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] deg = new int[numCourses];
        Map<Integer,List<Integer>> map = new HashMap<>();
        for (int[] p : prerequisites) {
            int i = p[1];
            int j = p[0];
            if(map.containsKey(i)==false){
                map.put(i,new LinkedList<Integer>());
            }
            List<Integer> l = map.get(i);
            l.add(j);
            deg[j]++;
        }
        List<Integer> zeroDeg = new LinkedList<>();
        for (int i = 0; i < deg.length; i++) {
            if(deg[i]==0) zeroDeg.add(i);
        }
        while(zeroDeg.isEmpty()==false){
            int node = zeroDeg.get(0);
            zeroDeg.remove(0);
                for (Integer n : map.getOrDefault(node,new LinkedList<>())) {
                    deg[n]--;
                    if(deg[n]==0) zeroDeg.add(n);
            }
        }
        for (Integer i : deg) {
            if(i!=0) return false;
        }
        return true;
    }
}